import {Injectable} from '@angular/core';

export interface PathItem {
  id: string
  index: number
}

@Injectable({
  providedIn: 'root'
})
export class PathService {

  path: PathItem[] = []

  constructor() {
  }

  reload(path: string | undefined) {
    if (path === undefined) {
      this.path = PathService.parsePath(undefined)
    } else {
      this.path = PathService.parsePath(path)
    }
  }

  getFilePath(): string {
    return this.path.map(item => item.id).join('/')
  }

  matchCurrentPath(p: string): boolean {
    return this.matchPath(this.getFileUrl(), p)
  }

  matchPath(a: string, b: string): boolean {
    return decodeURIComponent(a) === decodeURIComponent(b)
  }

  getFileUrl(newFilename: string | null = null): string {
    const items = this.copyPathItemIgnoreDelimiter()
    if (newFilename !== null) {
      items.push(newFilename)
    }
    let url = items.join('/')
    return encodeURIComponent(url)
  }

  enter(item: PathItem): string {
    let hasMatched = false
    let matchedIdx = -1
    this.path.some((pathItem) => {
      const matched = item.index == pathItem.index
      if (matched) {
        hasMatched = true
        matchedIdx = item.index
      }
      return matched
    })

    if (!hasMatched) {
      return this.getFileUrl()
    }

    const pathItems = []
    for (let i = 1; i <= matchedIdx; i++) {
      pathItems.push(this.path[i].id)
    }
    return encodeURIComponent(pathItems.join('/'))
  }

  private copyPathItemIgnoreDelimiter(): string[] {
    let newArray: string[] = []
    this.path.forEach((item) => {
      if (item.id !== '/') {
        newArray = newArray.concat(item.id)
      }
    })
    newArray.shift()
    return newArray
  }

  private static parsePath(path: string | undefined): PathItem[] {
    if (path === undefined) {
      return [{
        index: 0,
        id: 'home'
      }]
    }

    let items: string[] = ['home']
    try {
      PathService.getPurePathItems(path).forEach(it => {
        items.push(it)
      })
    } catch (e) {
      items = ['home']
    }
    return items.map((value, _index) => {
      return {
        index: _index,
        id: value
      }
    })
  }

  private static getPurePathItems(p: string): string[] {
    const items: string[] = []
    const pathItems = p.split('/')
    pathItems.forEach((it) => {
      if (it !== '/' && it !== '') {
        items.push(it)
      }
    })
    return items
  }
}
